<?php

/**
 * 商品总数据统计
 * @author jc
 */
namespace app\statis\model;

use app\common\model\StatProductSales;
use app\statis\lib\TimeStatistic;
use think\Exception;

class StatProductSalesModel extends StatProductSales
{
    /**
     * 订单商品统计
     *
     * @param $start
     * @param $end
     * @param $address_type [1为物流，2为自提]
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function statistic($start, $end, $address_type)
    {
        $coreM              = new CoreOrderModel();
        $productM           = new ProductModel();
        /* 统计汇总*/
        $statistic_data     = [];
        /*获取统计数据*/
        $order_product_list = $coreM->getProductByTime($start, $end, $address_type);
        if (empty($order_product_list)) {
            return $statistic_data;
        }

        /*单独针对商品进行统计*/
        /*计算商品下单人数*/
        $product_buyer_num_list = $this->calcProductBuyerNum($order_product_list);
        /*统计数据备忘：该商品下单人数，销量，销售金额，各配送方式下单数*/
        foreach ($order_product_list as $k => $o) {
            foreach ($o['product'] as $i => $product) {
                $product_info = $productM->getOneById($product['product_id']);
                if (empty($product_info)) {
                    throw new Exception('商品不存在');
                }
                $product_info = $product_info->toArray();

                if (!isset($statistic_data[$product['product_id']])) {
                    $statistic_data[$product['product_id']] = [
                        'sales'                         => 0, /*销量*/
                        'total_amount'                  => 0, /*销售金额*/
                        'product_id'                    => $product['product_id'],
                        'stat_start_time'               => $start,
                        'stat_end_time'                 => $end,
                        'cur_address_type'              => $address_type,
                        'stat_time'                     => TimeStatistic::getStatTime($end),
                        'cur_cate_id'                   => $product_info['cate']['product_category_id']??0,
                        'cur_cate_name'                 => $product_info['cate']['cate_name']??'',
                        'cur_is_show'                   => $product_info['is_show'],
                        'cur_is_recommend'              => $product_info['is_recommend'],
                        'cur_product_start_time'        => $product_info['product_start_time'],
                        'cur_product_end_time'          => $product_info['product_end_time'],
                        'cur_estimated_delivery_time'   => $this->getEstimatedDeliveryTime($o, $product_info, $address_type),
                        'buyer_num'                     => $product_buyer_num_list[$product['product_id']]['buyer_num']??0,
                        'create_time'                   => time(),
                    ];
                }

                $tmp                                                    = $statistic_data[$product['product_id']];
                $statistic_data[$product['product_id']]['sales']        = $tmp['sales'] + $product['number'];
                $statistic_data[$product['product_id']]['total_amount'] = (int)($tmp['total_amount'] + bcmul($product['price'] * $product['number'], 100, 2));
            }
        }

        $statistic_data = array_values($statistic_data);

        if (!$this->insertAll($statistic_data)) {
            throw new Exception('针对单独商品的统计入库失败');
        }

    }

    /**
     * 获取商品预计发货时间
     *
     * @param array $order
     * @param array $product 商品详情
     * @param int $address_type 配送方式：1为物流，2为自提
     * @return false|int
     */
    public function getEstimatedDeliveryTime($order, $product, $address_type)
    {
        if ($address_type == 1) {
            $after_order_delivery = $product['after_order_delivery'];
            if (empty($after_order_delivery)) {
                $after_order_delivery = 1;
            }

            $tmp_day = '+' . $after_order_delivery . ' day';
            $time = strtotime($tmp_day, strtotime($order['create_time']));
        } else { /*自提*/
            $time = $product['delivery_time'];
        }

        return $time;
    }

    /**
     * 计算统计时间段内
     * 商品购买人数
     *
     * @param array $order_product_list 订单商品数组
     * @return array $product_buyer_list
     *
     * [
     *      0 => [
     *          'user' => [ // 用户ID与该id购买次数
     *              11 => 2,
     *              12 => 1,
     *              ...
     *          ],
     *          'buyer_num' => 3 // 该商品购买人数（每个人只算1个）
     *      ],
     *      ....
     * ]
     *
     */
    public function calcProductBuyerNum($order_product_list)
    {
        $product_buyer_list = [];
        foreach ($order_product_list as $index => $item) {
            foreach ($item['product'] as $k => $p) {
                if (!isset($product_buyer_list[$p['product_id']]['user'][$item['user_id']])) {
                    $product_buyer_list[$p['product_id']]['user'][$item['user_id']] = 0;
                }
                $product_buyer_list[$p['product_id']]['user'][$item['user_id']] += 1;
            }
        }

        if (empty($product_buyer_list)) {
            return $product_buyer_list;
        }

        foreach ($product_buyer_list as $product_id => $item) {
            $buy_num = 0;
            if (!empty($item['user'])) {
                foreach ($item['user'] as $user_id => $num) {
                    $buy_num += 1;
                }
            }

            $product_buyer_list[$product_id]['buyer_num'] = $buy_num;

        }

        return $product_buyer_list;
    }
}